import { execSync } from 'node:child_process'
import { readFileSync, readdirSync, statSync } from 'node:fs'
import { join } from 'node:path'

const root = process.cwd()
const packagesDir = join(root, 'packages')

function readJSON(p) { return JSON.parse(readFileSync(p, 'utf8')) }

function getPackages() {
  return readdirSync(packagesDir)
    .map(name => ({ name, dir: join(packagesDir, name) }))
    .filter(x => statSync(x.dir).isDirectory())
    .map(x => ({ ...x, pkg: readJSON(join(x.dir, 'package.json')) }))
}

const tag = process.argv.includes('--tag') ? process.argv[process.argv.indexOf('--tag') + 1] : undefined
const access = process.argv.includes('--access') ? process.argv[process.argv.indexOf('--access') + 1] : 'public'

const list = getPackages()
for (const p of list) {
  console.log(`\nPublishing ${p.pkg.name}@${p.pkg.version} ...`)
  try {
    execSync('npm run build', { cwd: p.dir, stdio: 'inherit' })
    const cmd = ['npm', 'publish', '--access', access]
    if (tag) cmd.push('--tag', tag)
    execSync(cmd.join(' '), { cwd: p.dir, stdio: 'inherit' })
  } catch (e) {
    console.error(`Publish failed for ${p.pkg.name}:`, e.message)
    process.exitCode = 1
  }
}


